package org.snail.proxy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;


/**
 * 调用代理,目前只支持bytebuddy代理
 *
 * Created by fish on 17/8/18.
 */
public class Proxies<T> {

    /**
     * 接口调用代理
     *
     * @param interfaceType
     * @param handler
     */
    public static <T> T newProxy(Class<T> interfaceType, Object handler) {
        try {
            Class<? extends T> clazz = new ByteBuddy()
                    .subclass(interfaceType)
                    .method(ElementMatchers.isDeclaredBy(interfaceType))
                    .intercept(MethodDelegation.to(handler, "handler"))
                    .make()
                    .load(interfaceType.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                    .getLoaded();

            return clazz.newInstance();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
